package com.xuxu.blog.service.slef;

import com.xuxu.blog.entity.bean.Video;
import com.xuxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * @className: FileService
 * @author: Maxuxu
 * @date: 2022/8/27 13:40
 * @description: 文件的操作，包括上传下载
 */
@Slf4j
public class FileService {

    @Autowired
    private static String FILE_ADDRESS;
    @Value("${file_address}")
    public void setFileAddress(String fileAddress) {
        FILE_ADDRESS = fileAddress;
    }

    public static Video DownLoad(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        byte[] bytes = new byte[inputStream.available()];
        ByteBuffer wrap = ByteBuffer.wrap(bytes);
        log.info("buffer是：{}",wrap);
        Video video=new Video();
        if (!file.isEmpty()) {
            //存放地址
            String path = "D:\\test\\download\\";
            System.out.println("path: "+path);
            //如果父文件夹不存在 则创建文件夹 文件夹为path,视频名字file.getOriginalFilename()
            File filepath = new File(path, file.getOriginalFilename());
            if (!filepath.getParentFile().exists()) {
                log.error("文件不存在：{},创建文件");
                filepath.getParentFile().mkdirs();
            }
            File fi = new File(path + File.separator + file.getOriginalFilename());
            //下载到本地
            file.transferTo(fi);
            //获取绝对路径
            String localAddress = fi.getAbsolutePath();
            System.out.println("存入本地文件地址:" + localAddress);
            video.setLocalAddress(localAddress);
            //获取后缀名
            String suffix=localAddress.substring(localAddress.lastIndexOf("."), localAddress.length());
            System.out.println("后缀名:" + suffix);
            video.setSuffix(suffix);
            video.setFile(fi);
            video.setVideoName(originalFilename);

        }
        else {
            return null;
        }
        return video;
    }
}
